import * as echarts from 'echarts';
import { ChartResizer } from './chartResize';

/**
 * 安全初始化ECharts图表
 * 确保DOM元素有尺寸后再初始化图表
 * 
 * @param domId DOM元素ID
 * @param chartId 图表唯一标识符（用于ChartResizer）
 * @param options 图表配置选项
 * @param maxRetries 最大重试次数
 * @param retryInterval 重试间隔（毫秒）
 * @returns 返回图表实例或null
 */
export function initChartSafely(
  domId: string,
  chartId: string,
  options?: echarts.EChartsOption,
  maxRetries: number = 10,
  retryInterval: number = 100
): Promise<echarts.ECharts | null> {
  return new Promise((resolve) => {
    let retries = 0;
    
    function tryInit() {
      const chartDom = document.getElementById(domId);
      if (!chartDom) {
        if (retries < maxRetries) {
          retries++;
          setTimeout(tryInit, retryInterval);
        } else {
          console.warn(`Chart DOM element "${domId}" not found after ${maxRetries} retries`);
          resolve(null);
        }
        return;
      }
      
      // 检查DOM元素是否有尺寸
      const { clientWidth, clientHeight } = chartDom;
      if (clientWidth <= 0 || clientHeight <= 0) {
        if (retries < maxRetries) {
          retries++;
          setTimeout(tryInit, retryInterval);
        } else {
          console.warn(`Chart DOM element "${domId}" has no dimensions after ${maxRetries} retries`);
          resolve(null);
        }
        return;
      }
      
      try {
        // 初始化图表
        const chart = echarts.init(chartDom);
        
        // 设置选项
        if (options) {
          chart.setOption(options);
        }
        
        // 注册到ChartResizer
        ChartResizer.getInstance().register(chartId, chart, chartDom);
        
        resolve(chart);
      } catch (error) {
        console.error(`Failed to initialize chart "${domId}":`, error);
        resolve(null);
      }
    }
    
    tryInit();
  });
}

/**
 * 在Vue组件中使用的图表初始化函数
 * 适用于setup函数中
 * 
 * @param domId DOM元素ID
 * @param chartId 图表唯一标识符
 * @param options 图表配置选项
 * @returns 返回包含图表实例和更新函数的对象
 */
export function useChart(
  domId: string,
  chartId: string,
  options?: echarts.EChartsOption
) {
  let chartInstance: echarts.ECharts | null = null;
  
  // 初始化图表
  async function initChart() {
    chartInstance = await initChartSafely(domId, chartId, options);
    return chartInstance;
  }
  
  // 更新图表选项
  function updateChart(newOptions: echarts.EChartsOption, notMerge: boolean = false) {
    if (chartInstance) {
      chartInstance.setOption(newOptions, notMerge);
    }
  }
  
  // 销毁图表
  function disposeChart() {
    if (chartInstance) {
      ChartResizer.getInstance().unregister(chartId);
      chartInstance.dispose();
      chartInstance = null;
    }
  }
  
  // 重新调整图表大小
  function resizeChart() {
    if (chartInstance) {
      chartInstance.resize();
    }
  }
  
  return {
    initChart,
    updateChart,
    disposeChart,
    resizeChart,
    getChartInstance: () => chartInstance
  };
} 